package com.yunhe.abnormal.repository.data.impl;

import com.yunhe.abnormal.repository.data.AlarmEventQuery;
import com.yunhe.common.util.QueryUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 告警记录自定义查询
 * @author liuronglei
 */
@Service
public class AlarmEventQueryImpl implements AlarmEventQuery {
    @Autowired
    private EntityManager entityManager;

    /**
     * SQL总体逻辑为：
     * select from_unixtime(t.start_rtime/1000,'%Y-%m-%d') as dtime,count(1) as mycount
     * from data_alarm_event
     * where xxx=xxx
     * group by from_unixtime(t.start_rtime/1000,'%Y-%m-%d')
     */
    @Override
    public Map<String, Integer> getAlarmCountByDate(String timePattern,
                                                    List<Long> stationIds,
                                                    Long devId,
                                                    Long abnormalStatusId,
                                                    Long alarmLevelId,
                                                    List<String> dtime) {
        // 定义参数下标，用于Query参数设置
        int paramIndex = 0;
        StringBuilder sb = new StringBuilder("select FROM_UNIXTIME(start_rtime/1000,?) as dtime,count(1) as mycount")
                .append(" from data_alarm_event");
        // 组装参数下标和参数对应的Map
        Map<Integer, Object> parameter = new HashMap<>();
        // 组装条件列表
        List<String> condition = new ArrayList<>();
        parameter.put(++paramIndex, timePattern);
        if (stationIds != null) {
            StringBuilder inSb = new StringBuilder("station_id in (");
            for (int i = 0; i < stationIds.size(); i++) {
                if (i == 0) {
                    inSb.append("?");
                } else {
                    inSb.append(",?");
                }
                parameter.put(++paramIndex, stationIds.get(i));
            }
            inSb.append(")");
            condition.add(inSb.toString());
        }
        if (devId != null) {
            condition.add("dev_id=?");
            parameter.put(++paramIndex, devId);
        }
        if (abnormalStatusId != null) {
            condition.add("abnormal_status_id=?");
            parameter.put(++paramIndex, abnormalStatusId);
        }
        if (alarmLevelId != null) {
            condition.add("alarm_level_id=?");
            parameter.put(++paramIndex, alarmLevelId);
        }
        if (dtime != null && dtime.size() > 0) {
            if (dtime.size() == 1) {
                condition.add("start_time=?");
                parameter.put(++paramIndex, dtime.get(0));
            } else if (dtime.size() == 2) {
                condition.add("start_time>=?");
                condition.add("start_time<=?");
                parameter.put(++paramIndex, dtime.get(0));
                parameter.put(++paramIndex, dtime.get(1));
            }
        }
        sb.append(QueryUtil.getConditionStr(condition))
                .append(" group by FROM_UNIXTIME(start_rtime/1000,?)");
        parameter.put(++paramIndex, timePattern);
        Query query = entityManager.createNativeQuery(sb.toString());
        parameter.forEach(query::setParameter);
        List<Object[]> list = query.getResultList();
        Map<String, Integer> result = new HashMap<>();
        if (list != null) {
            list.forEach(objects -> {
                // 为了避免FROM_UNIXTIME后日期字符串为空，判断一下空值
                if (objects[0] != null) {
                    result.put(objects[0].toString(), Integer.parseInt(objects[1].toString()));
                }
            });
        }
        return result;
    }
}
